package com.mutouren.modules.org.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mutouren.common.entity.ValidState;
import com.mutouren.common.orm.spring.BaseServiceImpl;
import com.mutouren.modules.org.dao.FunctionDao;
import com.mutouren.modules.org.model.Function;
import com.mutouren.modules.org.service.FunctionService;

@Service
public class FunctionServiceImpl extends BaseServiceImpl<Function> implements FunctionService {
	
	@Resource
	private FunctionDao functionDao;	

	@Override
	public void afterPropertiesSet() throws Exception {
		this.baseDao = functionDao;		
	}
	
	@Override
	public int add(Function function) {
		Function parent = this.get(function.getParentId());
		function.setParentIdPath(parent.buildSelfIdPath());
		return this.functionDao.insert(function);
	}

	@Override
	public Function get(Object funcId) {
		if (funcId.equals(Function.ROOT_ID)) {
			return Function.createRoot();
		}
		
		Function result = this.functionDao.get(funcId);
		return result;
	}

	@Override
	public List<Function> selectByAppId(int appId, boolean isContainRoot) {
		List<Function> result = this.functionDao.selectByAppId(appId);
		
		if (isContainRoot) {
			result.add(0, Function.createRoot());
		}
		
		return result;
	}
	
	@Override
	public int setState(Function func) {
		Function obj = this.functionDao.get(func.getFuncId());
		
		if (func.getValidState() != ValidState.Delete) {
			throw new RuntimeException("不支持状态：" + func.getValidState());
		}
		
		obj.setValidState(func.getValidState());
				
		return this.functionDao.setState_selfAndChild(obj);
	}



}
